import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';

@Component({
  templateUrl: './virtual-scroll.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class VirtualScrollComponent {

  data: string[];
  selectedValue: string[];
  loading = false;
  private index = 100;
  private value: string;

  constructor(private cdr: ChangeDetectorRef) { }

  initData(value: string, cb: (arr: string[]) => void, length = 100, index = 0): void {
    let arr = [];
    if (value.length < 5) {
      arr = Array.from({ length }).map((_, key) => value + (index + key));
    } else {
      arr = [];
    }

    setTimeout(() => {
      cb(arr);
    }, 500);
  }

  inputChange(e: string): void {
    this.value = e;
    this.loading = true;
    this.initData(e, data => {
      this.loading = false;
      this.data = data;
      this.cdr.markForCheck();
    }, this.index, 0);
  }

  scroll(): void {
    const offsetIndex = 10;
    this.initData(this.value, data => {
      this.data = [...this.data, ...data];
      this.index += offsetIndex;
      this.cdr.markForCheck();
    }, offsetIndex, this.index);
  }

}
